package com.ruoyi.web.controller.tuike;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Executor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;


import com.ruoyi.common.utils.CalculationUtil;
import com.ruoyi.tiktok.domain.TFolder;
import com.ruoyi.tiktok.service.IFileService;
import com.ruoyi.tiktok.service.impl.AliOssService;
import com.ruoyi.tiktok.service.impl.TFolderService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.tiktok.domain.TFile;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.web.multipart.MultipartFile;

/**
 * fileUploadController
 * 
 * @author admin
 * @date 2024-08-22
 */
@RestController
@RequestMapping("/video-distribute/files")
public class TFileController extends BaseController
{
    @Autowired
    private IFileService tFileService;
    @Autowired
    public TFolderService tFolderService;
    @Value("${aliBucket.storageAddress}")
    private String storageAddress;
    @Value("${aliBucket.address}")
    private String aliBucketAddress;
    @Value("${aliBucket.bucketName}")
    private String bucketName;
    @Autowired
    private AliOssService aliOssService;

    @GetMapping("/folder/list")
    public AjaxResult listAll(@Param("parentId")Long parentId,@Param("folderId") Long folderId)
    {
        TFile tFile = new TFile();
        tFile.setParentId(parentId);
        List<TFile> list = tFileService.selectTFileList(tFile);
        List<TFolder> selectLIst = tFolderService.selectFolderList(folderId);

          for (int i = 0; i < selectLIst.size(); i++) {
            TFolder tFolder = selectLIst.get(i);
            TFile tmpFIle =new TFile();
            BeanUtils.copyProperties(tFolder,tmpFIle);
            tmpFIle.setType("0");
            list.add(tmpFIle);
        }

        return success(list);
    }
    @PostMapping("/searchAll/list")
    public AjaxResult getBindingList(@RequestBody List<TFile> qureyList)
    {
        List<TFile> finalBingList = new ArrayList<>();
        for (int i = 0; i < qureyList.size(); i++) {
            TFile tmpTFile = qureyList.get(i);
            if(tmpTFile.isSelected()){
                if(tmpTFile.getType().equals("0")){
                    // search sub file for this folder
                    TFile searchPara = new TFile();
                    searchPara.setParentId(tmpTFile.getFolderId());
                    List<TFile>  subList = tFileService.selectTFileList(searchPara);
                    finalBingList.addAll(subList);
                }else{
                    finalBingList.add(tmpTFile);
                }
            }
        }
        return success(finalBingList);
    }

    /**
     * 查询fileUpload列表
     */
    //@PreAuthorize("@ss.hasPermi('video-distribute:video-distribute:list')")
    @GetMapping("/list")
    public AjaxResult list(@Param("parentId")Long parentId,@Param("folderId") Long folderId)
    {
        TFile tFile = new TFile();
        tFile.setFolderId(folderId);
        tFile.setParentId(parentId);
        List<TFile> list = tFileService.selectTFileList(tFile);
        return success(list);
    }

    /**
     * 导出fileUpload列表
     */
    //@PreAuthorize("@ss.hasPermi('video-distribute:video-distribute:export')")
    @Log(title = "fileUpload", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TFile tFile)
    {
        List<TFile> list = tFileService.selectTFileList(tFile);
        ExcelUtil<TFile> util = new ExcelUtil<TFile>(TFile.class);
        util.exportExcel(response, list, "fileUpload数据");
    }

    /**
     * 获取fileUpload详细信息
     */
    //@PreAuthorize("@ss.hasPermi('video-distribute:video-distribute:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tFileService.selectTFileById(id));
    }

    /**
     * 新增fileUpload
     */
    //@PreAuthorize("@ss.hasPermi('video-distribute:video-distribute:add')")
    @Log(title = "insert TFile", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TFile tFile)
    {
        return toAjax(tFileService.insertTFile(tFile));
    }

    /**
     * 修改fileUpload
     */
    //@PreAuthorize("@ss.hasPermi('video-distribute:video-distribute:edit')")
    @Log(title = "fileUpdate", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TFile tFile)
    {
        return toAjax(tFileService.updateTFile(tFile));
    }

    /**
     * 删除fileUpload
     */
    //@PreAuthorize("@ss.hasPermi('video-distribute:video-distribute:remove')")
    @Log(title = "fileDelete", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tFileService.deleteTFileByIds(ids));
    }


    @Autowired
    private Executor threadPoolTaskExecutor;
    /**
     * 批量上传文件
     * @param parentId 文件夹id
     */
    @PostMapping("/addBatch")
    @Log(title = "fileUpload", businessType = BusinessType.IMPORT ,anonymousUser = "customer")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addBatch(@RequestPart(value = "file") @NotEmpty MultipartFile[] multipartFile,
                               @RequestParam("parentId") Long parentId) {
        List<TFile> filePos = new ArrayList<>();
        for (int i = 0; i < multipartFile.length; i++) {
            MultipartFile file = multipartFile[i];
            String fileName = file.getOriginalFilename();
            //设置文件code uuid + 文件后缀
            String splitStr [] = fileName.split("\\.");
            String code = UUID.randomUUID().toString().replaceAll("-", "");
            String storageFileName =  code + "." + splitStr[splitStr.length - 1];
            TFile filePo = new TFile();
            filePo.setParentId(parentId);
            // filePo.setCreateBy(getLoginUser().getUsername());
            String fileType = splitStr[splitStr.length - 1];
            if(!"mp4".equalsIgnoreCase(fileType) && !"mov".equalsIgnoreCase(fileType)){
                return error("文件类型出错误");
            }
            filePo.setType(fileType);
            //设置文件名
            filePo.setFileName(fileName);
            //云存储中文件名
            filePo.setStorageFileName(storageFileName);
            //设置路径
            String objectName = "videos/" + storageFileName;
            filePo.setFileUrl(storageAddress + "/" +objectName);
            //设置创建时间
            filePo.setCreateTime(new Date());
            //设置文件大小
            filePo.setFileSize(getMB(file.getSize()));
            filePo.setCoverImageAddress(storageAddress  +"/images/"+ code + ".jpeg");
            filePos.add(filePo);
            try {

                aliOssService.multiFileUpload(aliBucketAddress, bucketName, objectName, fileName, file);
                logger.info("start to generate Cover image...");
                aliOssService.generateCoverImage(file,"images/"+ code + ".jpeg");
                logger.info("end generate cover image...");

            } catch (IOException e) {
                logger.info(e.getMessage());
                throw new RuntimeException(e);
            }

        }
        //插入文件信息
        int addSize = tFileService.addList(filePos);
        return addSize > 0? success(filePos):error();

    }

    /**
     * 计算文件大小MB
     *
     * @param length 文件字节长度
     * @return 结果 MB
     */
    private String getMB(Long length) {
        return CalculationUtil.getCalculationUtil(CalculationUtil.getCalculationUtil(length, 1024, 3).divide(), 1024, 3).divide();
    }

}
